package org.example.leetcpde;

import org.junit.jupiter.api.Test;

public class searchRange {

    @Test
    void run() {
        int[] nums = {5, 7, 7, 8, 8, 10};
        searchRange(nums, 8);
    }


    public int[] searchRange(int[] nums,
                             int target) {
        int len = nums.length;
        if (len == 0) {
            return new int[]{-1, -1};
        }

        int l = searchLeft(nums, target);
        int r = searchRight(nums, target);
        if (l <= r) {
            return new int[]{l, r};
        }

        return new int[]{-1, -1};
    }

    int searchLeft(int[] nums,
                   int target) {
        int i = 0, j = nums.length - 1;
        for (; i <= j; ) {
            int mid = (i + j) >> 1, midValue = nums[mid];
            if (target <= midValue) {
                j = mid - 1;
            } else {
                i = mid + 1;
            }
        }

        return i;
    }

    int searchRight(int[] nums,
                    int target) {
        int i = 0, j = nums.length - 1;
        for (; i <= j; ) {
            int mid = (i + j) >> 1, midValue = nums[mid];
            if (target < midValue) {
                j = mid - 1;
            } else {
                i = mid + 1;
            }
        }

        return j;
    }
}
